#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import json
import openpyxl
import copy


class AppProject:

    def __init__(self):
        self.work_dir = os.path.dirname(os.path.realpath(__file__))
        self.xts_root = "/home/f00829171/mycode/gitee_openharmony/git/xts_acts_master"
        self.old_state_file = os.path.join('data', 'xts切换hvigor_0814.xlsx')
        self.titles = []

    def read_state_from_xlsx(self):
        wb = openpyxl.load_workbook(self.old_state_file)
        sheet = wb.active
        rows_data = list(sheet.rows)
        titles = [title.value for title in rows_data.pop(0)]
        self.titles = titles

        old_state = {}
        for a_row in rows_data:
            the_row_data = [cell.value for cell in a_row]
            row_dict = dict(zip(titles, the_row_data))
            app_path = row_dict.get('应用')
            old_state[app_path] = row_dict

        return old_state

    def write_xlsx(self, state_dict, xlsx_file):
        wb = openpyxl.Workbook()
        table = wb.active
        for i in range(len(self.titles)):
            col = i + 1
            #写表头
            table.cell(row=1, column=col, value=self.titles[i])

            #写数据
            row = 2
            for app_path in sorted(state_dict.keys()):
                content = state_dict[app_path].get(self.titles[i])
                if content:
                    table.cell(row, col).value = "{}".format(content)
                else:
                    table.cell(row, col).value = ''
                row = row + 1

        wb.save(os.path.join('data', xlsx_file))

    def get_hvigor_projects(self):
        cmd = "./get_app_projects.sh {} hvigor".format(self.xts_root)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        project_list = ret.stdout.decode().strip().replace("{}/".format((self.xts_root)), '').split('\n')
        project_dict = {}
        for project in project_list:
            project_dict[project] = ''
        return project_dict

    def get_non_hvigor_projects(self):
        cmd = "./get_app_projects.sh {} nonhvigor".format(self.xts_root)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        project_list = ret.stdout.decode().strip().replace("{}/".format((self.xts_root)), '').split('\n')
        project_dict = {}
        for project in project_list:
            project_dict[project] = ''
        return project_dict

    def remove_unexist_app(self, app_dict):
        new_app_dict = copy.deepcopy(app_dict)
        print("remove_unexist_app: len(app_dict)={}".format(len(app_dict)))
        for app_path in list(new_app_dict.keys()):
            if not os.path.exists(os.path.join(self.xts_root, app_path)):
                new_app_dict.pop(app_path)
        print("remove_unexist_app: len(new_app_dict)={}".format(len(new_app_dict)))
        return new_app_dict

    def merge_project(self, app_dict, non_hvigor_apps):
        new_app_dict = copy.deepcopy(app_dict)
        print("merge_project: len(app_dict)={}".format(len(app_dict)))
        for app_path in non_hvigor_apps:
            if app_path not in app_dict:
                new_app_dict[app_path] = {'应用': app_path, '状态': 'new'}
        print("merge_project: len(new_app_dict)={}".format(len(new_app_dict)))
        return new_app_dict

    def remove_hvigored_app(self, app_dict, hvigor_apps):
        new_app_dict = copy.deepcopy(app_dict)
        print("removed_hvigored_app: len(app_dict)={}".format(len(app_dict)))
        for app_path in list(new_app_dict.keys()):
            if app_path in hvigor_apps:
                new_app_dict.pop(app_path)
        print("removed_hvigored_app: len(new_app_dict)={}".format(len(new_app_dict)))
        return new_app_dict

    def get_comment_apps(self):
        cmd = "./get_comment_projects.sh {}".format(self.xts_root)
        ret = subprocess.run([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        project_list = ret.stdout.decode().strip().split('\n')
        project_dict = {}
        for project in project_list:
            project_dict[project] = ''
        return project_dict

    def remove_comment_app(self, app_dict):
        new_app_dict = copy.deepcopy(app_dict)
        print("remove_comment_app: len(app_dict)={}".format(len(app_dict)))
        comment_apps = self.get_comment_apps()
        print("comment_apps={}".format(comment_apps))
        for app_path in list(new_app_dict.keys()):
            if app_path in comment_apps:
                app_info = new_app_dict.get(app_path)
                app_info['状态'] = '不切换'
                app_info['修改人'] = '不切换'
        print("remove_comment_app: len(new_app_dict)={}".format(len(new_app_dict)))
        return new_app_dict

    def fill_type_of_apps(self, app_dict):
        new_app_dict = copy.deepcopy(app_dict)
        for app_path in list(new_app_dict.keys()):
            app_info = new_app_dict.get(app_path)
            if app_info.get('类型'):
                continue
            if os.path.exists(os.path.join(self.xts_root, app_path, "AppScope")):
                app_info['类型'] = 'STAGE'
            else:
                app_info['类型'] = 'FA'
        return new_app_dict

    def update_state_of_apps(self, app_dict):
        new_app_dict = copy.deepcopy(app_dict)
        for app_path in list(new_app_dict.keys()):
            app_info = new_app_dict.get(app_path)
            if app_info.get('状态') in ['close', 'block', 'reblock', 'revert', 'rework']:
                app_info['状态'] = 'open'

        return new_app_dict


def main():
    obj = AppProject()
    old_state = obj.read_state_from_xlsx()
    # print("old_state={}".format(old_state))
    obj.write_xlsx(old_state, "new_state_0.xlsx")

    hvigor_projects = obj.get_hvigor_projects()
    non_hvigor_projects = obj.get_non_hvigor_projects()
    # print("hvigor_projects={}".format(non_hvigor_projects))
    # print("non_hvigor_projects={}".format(non_hvigor_projects))
    print("len(hvigor_projects)={}".format(len(hvigor_projects)))
    print("len(non_hvigor_projects)={}".format(len(non_hvigor_projects)))

    new_apps = old_state
    new_apps = obj.remove_unexist_app(new_apps)
    obj.write_xlsx(new_apps, "new_state_1.xlsx")

    new_apps = obj.merge_project(new_apps, non_hvigor_projects)
    obj.write_xlsx(new_apps, "new_state_2.xlsx")

    new_apps = obj.remove_hvigored_app(new_apps, hvigor_projects)
    obj.write_xlsx(new_apps, "new_state_3.xlsx")

    new_apps = obj.remove_comment_app(new_apps)
    obj.write_xlsx(new_apps, "new_state_4.xlsx")

    new_apps = obj.fill_type_of_apps(new_apps)
    obj.write_xlsx(new_apps, "new_state_5.xlsx")
    new_apps = obj.update_state_of_apps(new_apps)
    obj.write_xlsx(new_apps, "new_state_6.xlsx")


if __name__ == "__main__":
    sys.exit(main())
